package com.xsir.ditan.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xsir.ditan.admin.constant.UserConstant;
import com.xsir.ditan.admin.entity.User;
import com.xsir.ditan.admin.mapper.UserMapper;
import com.xsir.ditan.admin.query.UserQuery;
import com.xsir.ditan.admin.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xsir.ditan.admin.vo.UserVo;
import com.xsir.ditan.miniprogram.entity.Certificate;
import com.xsir.ditan.miniprogram.service.ICertificateService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xsir
 * @since 2021-02-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ICertificateService certificateService;
    
    @Override
    public Map<String, Object> getList(UserQuery userQuery) {
        // 查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 人员姓名/手机号
        if (!StringUtils.isEmpty(userQuery.getKeywords())) {
            queryWrapper.like("real_name", userQuery.getKeywords()).or().like("phone", userQuery.getKeywords());
        }
        // 性别:1男 2女 3保密
        if (userQuery.getGender() != null) {
            queryWrapper.eq("gender", userQuery.getGender());
        }
        // 状态：1正常 2禁用
        if (userQuery.getStatus() != null) {
            queryWrapper.eq("status", userQuery.getStatus());
        }
    
        // 分页查询数据
        IPage<User> page = new Page<>(userQuery.getPage(), userQuery.getLimit());
        IPage<User> userPage = userMapper.selectPage(page, queryWrapper);
        List<User> users = userPage.getRecords();
        List<UserVo> userVoList = new ArrayList<>();
        if(!users.isEmpty()) {
            users.forEach(user -> {
                UserVo userVo = new UserVo();
                BeanUtils.copyProperties(user, userVo);
                // 性别描述
                if(userVo.getGender() != null && userVo.getGender() > 0) {
                    userVo.setGenderName(UserConstant.GENDER.get(userVo.getGender()));
                }
                // 状态描述
                if (userVo.getStatus() != null && userVo.getStatus() > 0) {
                    userVo.setStatusName(UserConstant.STATUS.get(userVo.getStatus()));
                }
                userVoList.add(userVo);
            });
        }
        
        // 返回数据
        Map<String,Object> data = new HashMap<>(4);
        data.put("data", userVoList);
        data.put("code", 0);
        data.put("count", userPage.getTotal());
        return data;
    }
    
    @Override
    public Map<String, Object> info(Integer id) {
        User user = userMapper.selectById(id);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        return JSON.parseObject(JSON.toJSONString(userVo), new TypeReference<Map<String,Object>>(){});
    }
    
    @Override
    public int cert(Integer userId, MultipartFile idCardPros, MultipartFile idCardCons) {
        Certificate certificate = certificateService.getOne(new QueryWrapper<Certificate>().eq("uid", userId));
        String filePath = System.getProperty("user.dir") + "/src/main/resources/static/upload/";
        // 糟糕的代码和逻辑，想吐！（偏偏还是自己写的）
        if(certificate == null) {
            certificate = new Certificate();
            certificate.setUid(userId);
        }
        if(idCardPros != null) {
            File dest = new File(filePath + "uid" + userId + "_idCardPros.jpg");
            try {
                idCardPros.transferTo(dest);
                certificate.setIdCardPros("http://localhost:8080/static/upload/uid" + userId + "_idCardPros.jpg");
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
        }
        if(idCardCons != null) {
            File dest = new File(filePath + "uid" + userId + "_idCardCons.jpg");
            try {
                idCardCons.transferTo(dest);
                certificate.setIdCardCons("http://localhost:8080/static/upload/uid" + userId + "_idCardCons.jpg");
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
        }
        
        certificateService.insertOrUpdate(certificate);
        User user = getById(userId);
        user.setStatus(2);
        updateById(user);
        
        return 1;
    }
}
